package com.ssmk.module.shoppingcar.order;

import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.pingplusplus.android.Pingpp;
import com.ssmk.R;
import com.ssmk.base.MVPBaseActivity;
import com.ssmk.module.shoppingcar.adapter.WaitPayInfoAdapter;
import com.ssmk.module.shoppingcar.bean.OrderAllBean;
import com.ssmk.utlis.GetCharge;
import com.ssmk.utlis.PopUtils;

import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.ssmk.R.id.orderdetails_cancel;

public class WaitPayActivity extends MVPBaseActivity implements View.OnClickListener {

    @BindView(R.id.orderdetails_recycler)
    RecyclerView mOrderdetailsRecycler;
    @BindView(orderdetails_cancel)
    Button mOrderdetailsCancel;
    @BindView(R.id.waitpay_delete_order)
    Button waitpayDeleteOrder;
    @BindView(R.id.orderdetails_submit)
    Button mOrderdetailsSubmit;
    @BindView(R.id.top_iv_back)
    ImageView mTopIvBack;
    @BindView(R.id.top_tv_title)
    TextView mTopTvTitle;
    @BindView(R.id.orderdetails_should_money)
    TextView orderdetails_should_money;
    private PopupWindow popWin;
    private OrderAllBean.DataBean dataBean;
    private WaitPayInfoAdapter payAdapter;
    private static String YOUR_URL ="http://218.244.151.190/demo/charge";
    public static final String CHARGE_URL = YOUR_URL;
    private static final String CHANNEL_WECHAT = "wx";
    private static final String CHANNEL_ALIPAY = "alipay";
    public static final boolean LIVEMODE = false;
    private LinearLayout pay_zhifubao;
    private LinearLayout pay_wx;
    private Button cancel_pay;


    @Override
    protected void initview() {
        Resources res = this.getResources();
        String title = res.getString(R.string.order_details);
        mTopTvTitle.setText(title);

        dataBean = (OrderAllBean.DataBean) getIntent().getSerializableExtra("WaitPay");
    }
    @Override
    protected void initdata() {
        mOrderdetailsRecycler.setLayoutManager(new LinearLayoutManager(this));
        payAdapter = new WaitPayInfoAdapter(this, dataBean);
        mOrderdetailsRecycler.setAdapter(payAdapter);

        mTopIvBack.setOnClickListener(this);
        mOrderdetailsCancel.setOnClickListener(this);
        mOrderdetailsSubmit.setOnClickListener(this);
        waitpayDeleteOrder.setOnClickListener(this);
    }

    @Override
    protected int layoutRes() {
        return R.layout.activity_wait_pay;
    }

    @Override
    public void UpData(Object o) {
        OrderAllBean orderAllBean = (OrderAllBean)o;
        if (orderAllBean != null){
            if (orderAllBean.getCode() == 200){
                Toast.makeText(WaitPayActivity.this,orderAllBean.getMsg(),Toast.LENGTH_SHORT).show();
                mOrderdetailsCancel.setVisibility(View.GONE);
                mOrderdetailsSubmit.setVisibility(View.GONE);
                waitpayDeleteOrder.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.top_iv_back:
                finish();
                break;
            case orderdetails_cancel:
                //取消订单AllOrderAdapter adapter, Context context, String orderId, int order, String flag
                //AllOrderPresenter presenter = new AllOrderPresenter(null,WaitPayActivity.this,dataBean.getOrderId(),0);
                //presenter.GetDataModel();
                break;
            case R.id.orderdetails_submit:
                View view = PopUtils.getPopView(this);
                final PopupWindow popUpWindow = PopUtils.getPopUpWindow(view);
                PopUtils.showPop(this,v,popUpWindow);//弹出pop
                pay_zhifubao = (LinearLayout)view.findViewById(R.id.pay_zhifubao);
                pay_wx = (LinearLayout)view.findViewById(R.id.pay_wx);
                cancel_pay = (Button)view.findViewById(R.id.cancel_pay);

                pay_zhifubao.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Toast.makeText(WaitPayActivity.this,"支付宝",Toast.LENGTH_SHORT).show();
                        //selectedPay(CHANNEL_ALIPAY);
                    }
                });
                pay_wx.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Toast.makeText(WaitPayActivity.this,"微信",Toast.LENGTH_SHORT).show();
                    //selectedPay(CHANNEL_WECHAT);
                }
            });
                cancel_pay.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        popUpWindow.dismiss();
                    }
                });

                break;
            case R.id.waitpay_delete_order:

                break;


        }
    }

    //选择支付方式提交订单--weixin
    /*private void selectedPay(final String channel){
        //Log.i("=====", "onClick: " + s);
        Map<String, String> map1 = new HashMap<>();
        map1.put("token", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjI1MiwicHdkIjoiZTEwYWRjMzk0OWJhNTlhYmJlNTZlMDU3ZjIwZjg4M2UiLCJpYXQiOjE1MDA0MzYyNzg1MDIsImV4dCI6MTUwMTA0MTA3ODUwMn0.ws2972b0tfqUWbiluxEEtv_2mbAjZzk3k9lTFxyHIvA");
        map1.put("Content-Type", "application/json");
        RequestBody body = RequestBody.create(RetrofitClientUtlis.JSON, s);

        RetrofitClientUtlis.getInstance(this, Url.BASESUREORDER + "order/", map1)
                .createBaseApi()
                .executePostJson(
                        //Url.BASESUREORDER11,
                        "submitOrder.do",
                        body, new BaseObserBean2<SubmitOrderBean>(context, SubmitOrderBean.class) {
                            @Override
                            public void Next(SubmitOrderBean data) {
                                if (data.getCode() == 200) {
                                    Log.i("likaihu", "Next: " + data.getMsg());
                                    String replaceable = String.format("[%s, \\s.]",
                                            NumberFormat.getCurrencyInstance(Locale.CHINA).getCurrency().getSymbol(Locale.CHINA));
                                    String cleanString = orderdetails_should_money.getText().toString().replaceAll(replaceable, "");
                                    int amount = Integer.valueOf(new BigDecimal(cleanString).toString());

                                    new PaymentTask().execute(new PaymentRequest(channel, amount));

                                    *//*Intent intent = new Intent(OrderActivity.this, EvaluateActivity.class);
                                    startActivity(intent);*//*
                                }

                            }
                        });

    }*/

    class PaymentTask extends AsyncTask<PaymentRequest, Void, String> {

        @Override
        protected void onPreExecute() {
            //按键点击之后的禁用，防止重复点击
            pay_zhifubao.setOnClickListener(null);
            pay_wx.setOnClickListener(null);
            cancel_pay.setOnClickListener(null);

        }

        @Override
        protected String doInBackground(PaymentRequest... pr) {

            PaymentRequest paymentRequest = pr[0];
            String data = null;
            try {
                JSONObject object = new JSONObject();
                object.put("channel", paymentRequest.channel);
                object.put("amount", paymentRequest.amount);
                object.put("livemode", paymentRequest.livemode);
                String json = object.toString();
                //向Your Ping++ Server SDK请求数据
                data = GetCharge.postJson(CHARGE_URL, json);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return data;
        }

        /**
         * 获得服务端的charge，调用ping++ sdk。
         */
        @Override
        protected void onPostExecute(String data) {
            if(null == data){
                showMsg("请求出错", "请检查URL", "URL无法获取charge");
                return;
            }
            Log.d("charge", data);

            //除QQ钱包外，其他渠道调起支付方式：
            //参数一：Activity  当前调起支付的Activity
            //参数二：data  获取到的charge或order的JSON字符串
            Pingpp.createPayment(WaitPayActivity.this, data);//data--->charge

            //QQ钱包调用方式
            //参数一：Activity  当前调起支付的Activity
            //参数二：data  获取到的charge或order的JSON字符串
            //参数三：“qwalletXXXXXXX”需与AndroidManifest.xml中的scheme值一致
            //Pingpp.createPayment(ClientSDKActivity.this, data, "qwalletXXXXXXX");
        }

    }
    public void showMsg(String title, String msg1, String msg2) {
        String str = title;
        if (null !=msg1 && msg1.length() != 0) {
            str += "\n" + msg1;
        }
        if (null !=msg2 && msg2.length() != 0) {
            str += "\n" + msg2;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(WaitPayActivity.this);
        builder.setMessage(str);
        builder.setTitle("提示");
        builder.setPositiveButton("OK", null);
        builder.create().show();
    }

    class PaymentRequest {
        String channel;
        int amount;
        boolean livemode;

        public PaymentRequest(String channel, int amount) {
            this.channel = channel;
            this.amount = amount;
            this.livemode = LIVEMODE;
        }
    }


   /* private static String postJson(String urlStr, String json) throws IOException {
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(8000);
        conn.setReadTimeout(8000);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.getOutputStream().write(json.getBytes());

        if (conn.getResponseCode() == 200) {
            BufferedReader
                    reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            return response.toString();
        }
        return null;
    }
*/


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
    }
}
